﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Reflection;
using DotaHelp.Models;
using System.Web.Caching;

namespace System.Web.Mvc
{
    public static class UrlHelperExtension
    {
		public static string Version(this UrlHelper url)
		{
			return Assembly.GetExecutingAssembly().GetName().Version.ToString();
		}

        public static string Absolute(this UrlHelper url, string relativeOrAbsolute)
        {
            var uri = new Uri(relativeOrAbsolute, UriKind.RelativeOrAbsolute);
            if (uri.IsAbsoluteUri)
            {
                return relativeOrAbsolute;
            }
            // At this point, we know the url is relative.
            return VirtualPathUtility.ToAbsolute(relativeOrAbsolute);
        }

        public static Uri GetBaseUrl(this UrlHelper url)
        {
            var uri = new Uri(
                url.RequestContext.HttpContext.Request.Url,
                url.RequestContext.HttpContext.Request.RawUrl
            );
            var builder = new UriBuilder(uri)
            {
                Path = url.RequestContext.HttpContext.Request.ApplicationPath,
                Query = null,
                Fragment = null
            };
            return builder.Uri;
        }

        public static string ContentAbsolute(this UrlHelper url, string contentPath)
        {
            return new Uri(GetBaseUrl(url), url.Content(contentPath)).AbsoluteUri;
        }

		public static T Get<T>(this Cache cache, string key, object @lock, Func<T> selector)
		{
			object value;
			if ((value = cache.Get(key)) == null)
			{
				lock (@lock)
				{
					if ((value = cache.Get(key)) == null)
					{
						value = selector();
						cache.Insert(key, value, null,
						 Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration,
						 CacheItemPriority.Normal, null);
					}
				}
			}
			return (T)value;
		}

		public static object myLock = new object();

        public static string Image(this UrlHelper url, int id, bool strike = false)
        {
			Dictionary<int, Tuple<string, string>> imgs = url.RequestContext.HttpContext.Cache.Get<Dictionary<int, Tuple<string, string>>>("imgs", myLock,
			() =>
			{
				using (var model = new DotaModel())
				{
					model.WriteError("Images reload");
					return model.Images
						.Select(_=>new {_.Id, _.HosterUrl, _.StrikeHosterUrl})
						.ToDictionary(_ => _.Id, _ => new Tuple<string, string>(_.HosterUrl, _.StrikeHosterUrl));
				}
			} 
			);
			
			Tuple<string, string> img;
			if (imgs.TryGetValue(id, out img))
			{
				//var hosturl = !strike ? img.Item1 : img.Item2;
				return /*hosturl ??*/ url.Action(!strike ? "Image" : "StrikeImage", "Home", new { id });				
			}
			else
			{
				return "http://farm8.staticflickr.com/7273/6988667100_8e44f99871_m.jpg";
			}
        }

        public static string ContentWithVersion(this UrlHelper url, string contentPath)
        {
            return url.Content(contentPath) + "?" + Assembly.GetExecutingAssembly().GetName().Version;
        }
    }
}